# @Time : 2024-11-05 12:00
# @Author : Fioman 
# @Phone : 13149920693
"""
可以通过全局变量来进行多线程之间的通信,但是会面临一个问题就是线程不安全,就是可能存在多个线程同时操作
这个变量,互相使用的都是更改之前的那个值.验证失败了,即使没有加上lock,得到的结果依旧是0,但是加上lock是
比较安全的做法
"""
import threading

sharedVal = 0
lock = threading.Lock()


def increment():
    global sharedVal
    for _ in range(10000):
        with lock:
            sharedVal += 1


def decrement():
    global sharedVal
    for _ in range(10000):
        with lock:
            sharedVal -= 1


if __name__ == '__main__':
    threads = []
    for _ in range(1000):
        thread1 = threading.Thread(target=increment)
        thread2 = threading.Thread(target=decrement)
        threads.append(thread1)
        threads.append(thread2)
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    print(f"Final Value: {sharedVal}")
